<template>
  <div class="xtx-city" ref="target">
    <div class="select" @click="toggle()">
      <span v-if="fullLocation" class="value">{{ fullLocation }}</span>
      <span v-else class="placehodler">{{ placeholder }}</span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-if="isshow">
      <div class="loading" v-if="!currList.length"></div>
      <span
        class="ellipsis"
        @click="changeItem(item)"
        v-for="item in currList"
        :key="item.code"
        >{{ item.name }}</span
      >
    </div>
  </div>
</template>

<script>
import { computed, reactive, ref } from 'vue'
import { onClickOutside } from '@vueuse/core'
import axios from 'axios'
export default {
  name: 'XtxCity',
  props: {
    fullLocation: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      defulat: '请选择配送地址'
    }
  },
  setup(props, { emit }) {
    const target = ref(null)
    const isshow = ref(false)
    // 城市列表
    const cityList = ref([])
    // 收集用户点击数据
    const address = reactive({
      provinceCode: '',
      provinceName: '',
      cityCode: '',
      cityName: '',
      countyCode: '',
      countyName: '',
      fullLocation: ''
    })
    // 下拉框显示
    const show = async () => {
      isshow.value = true

      // 盒子显示的时候获取城市信息，展示到页面
      const data = await getCityList()
      cityList.value = data
      // 每次打开的时候到要重新收集数据
      for (const key in address) {
        address[key] = ''
      }
    }
    // 下拉框隐藏
    const hide = () => {
      isshow.value = false
    }
    // 切换下拉框显示隐藏
    const toggle = () => {
      isshow.value ? hide() : show()
    }

    // 点击目标元素之外，onClickOutside（目标元素，事件处理函数）
    onClickOutside(target, () => {
      //   console.log('你点击了元素外')
      hide()
    })

    // 获取城市数据
    // 1.数据在哪？ https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json
    // 2.何时获取？打开城市列表的时候，做个内存中缓存
    // 3.怎么使用数据？定义计算属性，根据点击的省份城市展示
    const getCityList = async () => {
      // 如果内存中有城市数据，直接返回
      if (window.cityList) {
        // console.log('读取缓存中数据')
        return window.cityList
      } else {
        // 内存中没有城市数据，发送请求，获取城市数据
        const { data } = await axios.get(
          'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json'
        )
        // 把数组存储到window对象缓存起来
        window.cityList = data
        return data
      }
    }

    // 点击选择城市
    const changeItem = (item) => {
      // 省份：level === 0
      if (item.level === 0) {
        address.provinceCode = item.code
        address.provinceName = item.name
      } else if (item.level === 1) {
        // 市：level === 1
        address.cityCode = item.code
        address.cityName = item.name
      } else if (item.level === 2) {
        // 区/县
        address.countyCode = item.code
        address.countyName = item.name
        hide()
        address.fullLocation = `${address.provinceName} ${address.cityName} ${address.countyName}`
        emit('change', address)
      }
    }
    // 计算属性，计算出当前所需展示的列表
    const currList = computed(() => {
      // 省份
      let list = cityList.value
      console.log(list, 'list')
      // 城市
      if (address.provinceCode) {
        list = list.find((item) => item.code === address.provinceCode).areaList
        console.log(list, 'list111')
      }
      // 地区
      if (address.cityCode) {
        list = list.find((item) => item.code === address.cityCode).areaList
      }
      return list
    })
    return { target, isshow, toggle, currList, changeItem }
  }
}
</script>
<style scoped lang="less">
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;
  left: 2px;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.acive {
      background-color: #fff;
    }
    .placehodler {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background-color: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    .loading {
      height: 290px;
      width: 100%;
      background: url(~@/assets/images/loading.gif) no-repeat center;
    }
    > span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background-color: #f5f5f5;
      }
    }
  }
}
</style>
